
import { message } from 'ant-design-vue/es'

/**
 * 设置缓存
 * @param {String 缓存名} name
 * @param {any 内容} content
 */
export function setStore(name, content) {
  if (!name) return
  
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取缓存
 * @param {String 缓存名} name
 */
export function getStore(name) {
  if (!name) return
  let str = window.localStorage.getItem(name)

  if (typeof str == 'string') {
    try {
      let obj = JSON.parse(str)
      if (typeof obj == 'object' && obj) {
        return obj
      } else {
        return str
      }
    } catch (err) {
      return str
    }
  }
}

/**
 * 删除缓存
 * @param {String 缓存名} name
 */
export function removeStore(name) {
  if (!name) return
  return window.localStorage.removeItem(name)
}

export function clearStore(name) {
  window.localStorage.clear()
}

/**
 * 判断数据格式
 * @param {*} data
 * @return { string }
 */
export function getType(obj) {
  let toString = Object.prototype.toString

  let map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }

  if (obj instanceof Element) {
    return 'element'
  }

  return map[toString.call(obj)]
}

/**
 * 对象深拷贝
 * @param {*} data
 */
export function deepClone(data) {
  let type = getType(data)
  let obj

  if (type === 'array') {
    obj = []
  } else if (type === 'object') {
    obj = {}
  } else {
    return data
  }

  if (type === 'array') {
    for (let i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (let key in data) {
      obj[key] = deepClone(data[key])
    }
  }

  return obj
}

/**
 * [时间格式转换]
 * @param  {[type]} date    [description]
 * @param  {[type]} formats [description]
 * @return {[type]}         [description]
 */
export function formatTime(date, formats) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  formats = formats || 'Y-m-d'
  return formats.replace(/Y|m|d|H|i|s/gi, (matches) => {
    return {
      Y: year,
      m: formatNumber(month),
      d: formatNumber(day),
      H: formatNumber(hour),
      i: formatNumber(minute),
      s: formatNumber(second)
    }[matches]
  })

  // return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 身份证号码
 * @param {*} Account
 */
export function checkBankNumber(Account) {
  if (Account == '' || Account == undefined) {
    return false
  }

  let lastNum = Account.substr(Account.length - 1, 1) //取出最后一位（与luhn进行比较）
  let first15Num = Account.substr(0, Account.length - 1) //前15或18位

  let newArr = new Array()
  for (let i = first15Num.length - 1; i > -1; i--) {
    //前15或18位倒序存进数组
    newArr.push(first15Num.substr(i, 1))
  }
  let arrJiShu = new Array() //奇数位*2的积 <9
  let arrJiShu2 = new Array() //奇数位*2的积 >9
  let arrOuShu = new Array() //偶数位数组

  for (let j = 0; j < newArr.length; j++) {
    if ((j + 1) % 2 == 1) {
      //奇数位
      if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2)
      else arrJiShu2.push(parseInt(newArr[j]) * 2)
    } //偶数位
    else arrOuShu.push(newArr[j])
  }

  let jishu_child1 = new Array() //奇数位*2 >9 的分割之后的数组个位数
  let jishu_child2 = new Array() //奇数位*2 >9 的分割之后的数组十位数

  for (let h = 0; h < arrJiShu2.length; h++) {
    jishu_child1.push(parseInt(arrJiShu2[h]) % 10)
    jishu_child2.push(parseInt(arrJiShu2[h]) / 10)
  }

  let sumJiShu = 0 //奇数位*2 < 9 的数组之和
  let sumOuShu = 0 //偶数位数组之和
  let sumJiShuChild1 = 0 //奇数位*2 >9 的分割之后的数组个位数之和
  let sumJiShuChild2 = 0 //奇数位*2 >9 的分割之后的数组十位数之和
  let sumTotal = 0

  for (let m = 0; m < arrJiShu.length; m++) {
    sumJiShu = sumJiShu + parseInt(arrJiShu[m])
  }
  for (let n = 0; n < arrOuShu.length; n++) {
    sumOuShu = sumOuShu + parseInt(arrOuShu[n])
  }
  for (let p = 0; p < jishu_child1.length; p++) {
    sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p])
    sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p])
  }

  //计算总和
  sumTotal =
    parseInt(sumJiShu) +
    parseInt(sumOuShu) +
    parseInt(sumJiShuChild1) +
    parseInt(sumJiShuChild2)

  //计算luhn值
  let k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10
  let luhn = 10 - k
  if (parseInt(lastNum) !== parseInt(luhn)) {
    return false
  } else {
    return true
  }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * 读取文件
 * @param {} file
 */
export function readFile(file) {
  return new Promise((resolve) => {
    let fileReader = new FileReader()

    fileReader.onload = (ev) => {
      resolve(ev.target.result)
    }

    fileReader.readAsBinaryString(file)
  })
}

/**
 * 下载文件 Blob
 * @param {*} fileBlob
 * @param {*} name
 * @param {*} type
 * @param {*} callback
 */
export function downFile(fileBlob, name, type) {
  let reader = new FileReader()
  reader.readAsDataURL(fileBlob)
  reader.onload = (ev) => {
    let a = document.createElement('a')

    a.download = name + '.' + type
    a.href = ev.target.result
    document.body.appendChild(a) // 修复firefox中无法触发click
    a.click()
  }
}

/**
 * 下载文件 url
 * @param {*} fileBlob
 * @param {*} name
 * @param {*} callback
 */
export function URLDownFile(url, name) {
  const link = document.createElement('a')
  link.style.display = 'none'
  link.setAttribute('href', url)
  if (name) {
    link.setAttribute('download', name)
  }

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 深度合并对象
 * @param {*} minor
 * @param {*} main
 * @returns
 */
export function mergeObject(minor = {}, main = {}) {
  let result = minor

  if (typeof minor != 'object' || typeof main != 'object') {
    return main
  }

  for (let key in main) {
    if (minor.hasOwnProperty(key)) {
      if (Array.isArray(minor[key]) && minor[key].length != main[key].length) {
        result[key] = mergeArray(minor[key], main[key])
      } else {
        result[key] = mergeObject(minor[key], main[key])
      }
    } else {
      result[key] = main[key]
    }
  }

  return result
}

/**
 * 合并数组
 * @param {*} minor
 * @param {*} main
 * @returns
 */
export function mergeArray(minor, main) {
  let result = minor
  for (let i = 0; i < minor.length; i++) {
    for (let j = 0; j < main.length; j++) {
      if (minor[i].remark == main[j].remark) {
        for (let key in main[j]) {
          if (Array.isArray(main[j][key])) {
            result[i][key] = mergeArray(result[i][key], main[j][key])
          } else {
            result[i][key] = main[j][key]
          }
        }
        break
      }
    }
  }

  return result
}

/**
 * 浮点数乘法运算
 * @param num1
 * @param num2
 */
export const floatMul = (num1, num2) => {
  let m = 0,
    s1 = num1.toString(),
    s2 = num2.toString()
  try {
    if (s1.split('.')[1] != undefined) {
      m += s1.split('.')[1].length
    }
  } catch (e) {}

  try {
    if (s2.split('.')[1] != undefined) {
      m += s2.split('.')[1].length
    }
  } catch (e) {}

  return (
    (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) /
    Math.pow(10, m)
  )
}

/**
 * 复制文本
 * @param content
 */
export function clipboard(content, tip) {
  navigator.clipboard.writeText(content)
  message.success(tip || '复制成功')
}
